package com.wang.transfer.controller;

import com.wang.common.common.AbstractController;
import com.wang.common.common.ErrorCode;
import com.wang.common.exception.BusinessException;
import com.wang.common.utils.Utils;
import com.wang.transfer.entity.ZipPath;
import com.wang.transfer.util.io.DifferentFileBuffered;
import com.wang.transfer.util.io.ServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class StreamController extends AbstractController {

    @Resource
    private DifferentFileBuffered differentFileBuffered;

    @Resource
    private ServletResponse servletResponse;

    @RequestMapping("/getFileStream.do")
    public void getFileStream(@PathParam("filepath") String filepath) throws IOException {
        if (Utils.isEmpty(filepath)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件路径不能为空");
        }
        differentFileBuffered.getFileStream(filepath, DifferentFileBuffered.ContentType.OCTET);
    }

    @RequestMapping("/getImageStream.do")
    public void getImageStream(@RequestParam("path") String path, @RequestParam("imageType") String imageType) throws IOException {
        if (Utils.isAnyBlank(path, imageType)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件路径或图片类型不能为空");
        }
        differentFileBuffered.getImageStream(path, imageType);
    }

    @RequestMapping("/getZipStream.do")
    public void getZipStream(@RequestParam("path") String path) throws IOException {
        if (Utils.isEmpty(path)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件路径不能为空");
        }
        differentFileBuffered.getZipStream(path);
    }

    @RequestMapping("/getZipStreamMore.do")
    public void getZipStreamMore(@RequestBody ZipPath zipPaths) throws IOException {
        if (Utils.isEmpty(zipPaths)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件路径不能为空");
        }
        final String[] path = {""};
        zipPaths.getPath().forEach(p -> {
            path[0] += ",";
            path[0] += p;
        });
        differentFileBuffered.getZipStream(path[0].substring(1));
    }

    @RequestMapping("/getJsonOrFileStream.do")
    public void getJsonOrFileStream(@PathParam("dataType") String dataType, @Nullable @PathParam("filePath") String filePath) throws IOException {
        servletResponse.doGet(dataType, filePath);
    }
}
